package com.afdor.rws.event.channel.aliyun.mq.topic;

import com.afdor.rws.annotation.extension.Extension;
import com.afdor.rws.event.Event;
import com.afdor.rws.event.channel.aliyun.mq.AbstractAliyunEventProducer;
import com.afdor.rws.event.channel.aliyun.mq.utils.AliyunMQUtils;
import com.afdor.rws.event.channel.client.producer.EventProducer;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.RawTopicMessage;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * 基于阿里云MQ发布订阅模式的事件生产者实现
 *
 * @author 悭梵
 * @date Created in 2018-08-16 10:20
 */
@Slf4j
@ToString
@EqualsAndHashCode
@Extension(value = "amq_topic", order = Extension.NORMAL_ORDER - 50, scope = Extension.Scope.PROTOTYPE, interfaceClass = EventProducer.class)
public class AliyunMQTopicEventProducer extends AbstractAliyunEventProducer {

    @Override
    public void doSendEvent(@NonNull Event event) {
        MNSClient mnsClient = getCloudAccount().getMNSClient();
        CloudTopic topic = mnsClient.getTopicRef(AliyunMQUtils.getTopicName(event.getEventSourceName()));
        try {
            RawTopicMessage message = new RawTopicMessage();
            message.setMessageBody((String) getSerialization().serialize(event));
            topic.publishMessage(message);
            if (log.isInfoEnabled()) {
                log.info("<===== 发送消息：" + event);
            }
        } catch (Exception e) {
            log.error("发送事件异常", e);
        }
    }
}
